<?php
class ProjectCommentsController extends AppController
{
    public $name = 'ProjectComments';
    public $components = array(
        'Email'
    );
    public $uses = array(
        'ProjectComment',
        'EmailTemplate',
    );
    public function beforeFilter()
    {
        if (!Configure::read('Project.is_project_comment_enabled')) {
            throw new NotFoundException(__l('Invalid request'));
        }
        parent::beforeFilter();
        if (!Configure::read('suspicious_detector.is_enabled') && !Configure::read('Project.auto_suspend_project_comment_on_system_flag')) {
            $this->ProjectComment->Project->Behaviors->detach('SuspiciousWordsDetector');
        }
    }
    public function index($project_id = null)
    {
        $this->pageTitle = __l('Project Comments');
        $conditions = array();
        $conditions['ProjectComment.project_id'] = $project_id;
        $project = $this->ProjectComment->Project->find('first', array(
            'conditions' => array(
                'Project.id' => $project_id,
            ) ,
            'fields' => array(
                'Project.slug','Project.project_comment_count'
            ) ,
            'recursive' => - 1
        ));
        if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
            if ($this->Auth->user('id')) {
                $conditions['ProjectComment.admin_suspend'] = '0';
            } else {
                $conditions['ProjectComment.admin_suspend'] = '0';
            }
        }
        $this->ProjectComment->recursive = 0;
        $this->paginate = array(
            'conditions' => $conditions,
            'contain' => array(
                'User' => array(
                    'UserAvatar' => array(
                        'fields' => array(
                            'UserAvatar.id',
                            'UserAvatar.filename',
                            'UserAvatar.dir',
                            'UserAvatar.width',
                            'UserAvatar.height'
                        )
                    ) ,
                    'fields' => array(
                        'username'
                    ) ,
                ) ,
                'Project' => array(
                    'fields' => array(
                        'Project.user_id'
                    )
                )
            ) ,
            'order' => array(
                'ProjectComment.id' => 'desc'
            )
        );
		if ($this->RequestHandler->prefers('json')) {
			$iphone_project_comments = $this->paginate();
			$iphone_project_comment = array();
			for($i=0;$i<count($iphone_project_comments);$i++)
			{	
				$month = date('F',strtotime($iphone_project_comments[$i]['ProjectComment']['created']));
				$year = date('Y',strtotime($iphone_project_comments[$i]['ProjectComment']['created']));
				$date = date('d',strtotime($iphone_project_comments[$i]['ProjectComment']['created']));
				$created = $month." ".$date;
				
				
				
				$image_options = array(
            			'dimension' => 'iphone_project_thumb',
            			'class' => '',
            			'alt' => 'alt',
            			'title' => 'title',
            			'type' => 'jpg'
        		);
				if(!empty($iphone_project_comments[$i]['User']['UserAvatar']))
				{
				$image_url = Router::url('/', true).$this->ProjectComment->Project->getImageUrl('UserAvatar', $iphone_project_comments[$i]['User']['UserAvatar'], $image_options);
				}
				else
				{
				$iphone_project_comments[$i]['User']['UserAvatar']['id'] = constant(sprintf('%s::%s', 'ConstAttachment', 'UserAvatar'));
				$image_url = Router::url('/', true).$this->ProjectComment->Project->getImageUrl('UserAvatar', $iphone_project_comments[$i]['User']['UserAvatar'], $image_options);
				}
				$iphone_project_comment[$i]['Comment_username'] = $iphone_project_comments[$i]['User']['username'];
				$iphone_project_comment[$i]['Comment_user_image'] = $image_url;
				$iphone_project_comment[$i]['Comment_created'] = $created;
				$iphone_project_comment[$i]['Comment'] = $iphone_project_comments[$i]['ProjectComment']['comment'];
			}
			
			$this->view = 'Json';
			$this->set('json',$iphone_project_comment);
		
		}
        $this->request->data['ProjectComment']['project_id'] = $project_id;
        $this->set('projectComments', $this->paginate());
        $this->set('project', $project);
    }
    public function view($id = null, $view_name = 'view')
    {
        $this->pageTitle = __l('Project Comment');
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $projectComment = $this->ProjectComment->find('first', array(
            'conditions' => array(
                'ProjectComment.id = ' => $id,
                'ProjectComment.admin_suspend ' => 0,
            ) ,
            'contain' => array(
                'User' => array(
                    'UserAvatar' => array(
                        'fields' => array(
                            'UserAvatar.id',
                            'UserAvatar.dir',
                            'UserAvatar.filename'
                        )
                    ) ,
                    'fields' => array(
                        'User.username'
                    )
                ) ,
                'Project' => array(
                    'fields' => array(
                        'Project.user_id'
                    )
                )
            ) ,
            'recursive' => 2,
        ));
        if (empty($projectComment)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->pageTitle.= ' - ' . $projectComment['ProjectComment']['id'];
        $this->set('projectComment', $projectComment);
        $this->render($view_name);
    }
    public function add()
    {
        $this->pageTitle = __l('Add Project Comment');
        if (!empty($this->request->data)) {
			$this->request->data['ProjectComment']['ip_id'] = $this->ProjectComment->toSaveIp();
            $this->ProjectComment->create();
            if ($this->ProjectComment->save($this->request->data)) {
                $projectComment = $this->ProjectComment->find('first', array(
                    'conditions' => array(
                        'ProjectComment.id' => $this->ProjectComment->id,
                    ) ,
                    'recursive' => - 1
                ));
                $project = $this->ProjectComment->Project->find('first', array(
                    'conditions' => array(
                        'Project.id' => $this->request->data['ProjectComment']['project_id']
                    ) ,
                    'contain' => array(
                        'User' => array(
                            'fields' => array(
                                'User.email',
                                'User.username'
                            )
                        ) ,
                        'ProjectFund' => array(
                            'fields' => array(
                                'ProjectFund.user_id'
                            )
                        ) ,
                        'ProjectFollower' => array(
                            'fields' => array(
                                'ProjectFollower.user_id'
                            )
                        ) ,
                    ) ,
                    'fields' => array(
                        'Project.id',
                        'Project.user_id',
                        'Project.name',
                        'Project.slug',
                    ) ,
                    'recursive' => 2
                ));
                // sending Mail to owner
                if (!$projectComment['ProjectComment']['admin_suspend']) {
                    $owner_user[] = $project['Project']['user_id'];
                    $return_owner_lists = $this->_sendAlertOnProjectComment(array_unique($owner_user) , $project, ConstProjectUsers::Owner);
                    // send mail to backed
                    $pledged_users = Set::extract('/ProjectFund/user_id', $project);
                    $pledged_user_lists = $this->_sendAlertOnProjectComment(array_unique($pledged_users) , $project, ConstProjectUsers::Backer, $return_owner_lists);
                    // send mail to followers
                    $follow_users = Set::extract('/ProjectFollower/user_id', $project);
                    $this->_sendAlertOnProjectComment(array_unique($follow_users) , $project, ConstProjectUsers::Follower, $pledged_user_lists);
                }
                if ($projectComment['ProjectComment']['admin_suspend']) {
                    $this->Session->setFlash(__l('Comment has been suspended due to containing suspicious words ') , 'default', null, 'error');
                    $this->set('projectComment', $projectComment);
                } else {
                    $this->Session->setFlash(__l('Comment has been added.') , 'default', null, 'success');
                    if (!$this->RequestHandler->isAjax()) {
                        $this->redirect(array(
                            'controller' => 'projects',
                            'action' => 'view',
                            $project['Project']['slug'],
                            'admin' => false
                        ));
                    } else {
                        // Ajax: return added answer
                        $this->setAction('view', $this->ProjectComment->id, 'view_ajax');
                    }
                }
            } else {
                $this->Session->setFlash(__l('Comment could not be added. Please, try again.') , 'default', null, 'error');
            }
        }
        $users = $this->ProjectComment->User->find('list');
        $projects = $this->ProjectComment->Project->find('list');
        $this->set(compact('users', 'projects'));
    }
    public function _sendAlertOnProjectComment($to_users, $project, $projectUserType, $user_lists = array())
    {
        if (!empty($to_users)) {
            $users = $this->ProjectComment->User->find('all', array(
                'conditions' => array(
                    'User.id' => $to_users
                ) ,
                'fields' => array(
                    'User.id',
                    'User.email',
                    'User.username',
                ) ,
                'recursive' => - 1
            ));
            // Send private messsage on project comment add
            $subject = __l('New Project Comment');
            $message = $this->Auth->User('username') . ' ' . __l('has commented on project') . ' "' . $project['Project']['name'] . '"';
            $message_id = $this->ProjectComment->Project->Message->sendNotifications($to_users, $subject, $message, $project['Project']['id']);
            foreach($users as $user) {
                if (!in_array($user['User']['id'], $user_lists)) {
                    $user_preference = $this->ProjectComment->_getPermissionPerference($user['User']['id']);
                    if (($projectUserType == ConstProjectUsers::Backer && $user_preference['UserPermissionPreference']['project_comment_mail_send_backer'] == 1) || ($projectUserType == ConstProjectUsers::Follower && $user_preference['UserPermissionPreference']['project_comment_mail_send_follower'] == 1) || ($projectUserType == ConstProjectUsers::Owner && $user_preference['UserPermissionPreference']['project_comment_mail_send_owner'] == 1)) {
                        $email_message = $this->EmailTemplate->selectTemplate('Project Comment Add Alert');
                        $emailFindReplace = array(
                            '##FROM_EMAIL##' => $this->ProjectComment->changeFromEmail(($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from']) ,
                            '##USERNAME##' => $user['User']['username'],
                            '##USER##' => $this->Auth->User('username') ,
                            '##SITE_NAME##' => Configure::read('site.name') ,
                            '##PROJECT_NAME##' => $project['Project']['name'],
                            '##PROJECT_LINK##' => Router::url(array(
                                'controller' => 'projects',
                                'action' => 'view',
                                $project['Project']['slug'],
                                '#_Comments',
                                'admin' => false
                            ) , true) ,
                            '##SITE_URL##' => Router::url('/', true) ,
                        );
                        $this->Email->from = ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'];
                        $this->Email->replyTo = ($email_message['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('EmailTemplate.reply_to_email') : $email_message['reply_to'];
                        $this->Email->to = $user['User']['email'];
                        $this->Email->subject = strtr($email_message['subject'], $emailFindReplace);
                        $this->Email->sendAs = !empty($email_message['is_html']) ? 'html' : 'text';
                        $this->Email->send(strtr($email_message['email_content'], $emailFindReplace));
                    }
                    $user_lists[] = $user['User']['id'];
                }
            }
        }
        return $user_lists;
    }
    public function delete($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $project = $this->ProjectComment->find('first', array(
            'conditions' => array(
                'ProjectComment.id' => $id
            ) ,
            'fields' => array(
                'Project.slug'
            )
        ));
        if ($this->ProjectComment->delete($id)) {
            $this->Session->setFlash(__l('Project Comment deleted') , 'default', null, 'success');
            $this->redirect(array(
                'controller' => 'projects',
                'action' => 'view',
                $project['Project']['slug']
            ));
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
    }
    public function admin_index()
    {
        $this->_redirectGET2Named(array(
            'q'
        ));
        $this->ProjectComment->recursive = 0;
        $conditions = array();
        if (!empty($this->request->params['named']['project_id'])) {
            $project_name = $this->ProjectComment->Project->find('first', array(
                'conditions' => array(
                    'Project.id' => $this->request->params['named']['project_id'],
                ) ,
                'fields' => array(
                    'Project.name',
                ) ,
                'recursive' => - 1,
            ));
            $this->pageTitle.= sprintf(__l('Project Comments new - %s') , $project_name['Project']['name']);
        } else {
            $this->pageTitle = __l('Project Comments');
        }
        if (!empty($this->request->params['named']['filter_id'])) {
            if ($this->request->params['named']['filter_id'] == ConstMoreAction::Suspend) {
                $conditions['ProjectComment.admin_suspend'] = 1;
                $this->pageTitle.= __l(' - Admin suspended ');
            } elseif ($this->request->params['named']['filter_id'] == ConstMoreAction::Active) {
                $conditions['ProjectComment.is_active'] = 1;
                $conditions['ProjectComment.admin_suspend'] = 0;
                $this->pageTitle.= __l(' - Active ');
            } elseif ($this->request->params['named']['filter_id'] == ConstMoreAction::Inactive) {
                $conditions['ProjectComment.is_active'] = 0;
                $this->pageTitle.= __l(' - Inactive ');
            } elseif ($this->request->params['named']['filter_id'] == ConstMoreAction::Flagged) {
                $conditions['ProjectComment.is_system_flagged'] = 1;
                $this->pageTitle.= __l(' - System flagged ');
            }
        }
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'day') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(ProjectComment.created) <= '] = 0;
            $this->pageTitle.= __l(' - Added today');
        }
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'week') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(ProjectComment.created) <= '] = 7;
            $this->pageTitle.= __l(' - Added in this week');
        }
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'month') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(ProjectComment.created) <= '] = 30;
            $this->pageTitle.= __l(' - Added in this month');
        }
        if (!empty($this->request->params['named']['q'])) {
            $conditions['AND']['OR'][]['Project.name LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $conditions['AND']['OR'][]['ProjectComment.comment LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $conditions['AND']['OR'][]['User.username LIKE'] = '%' . $this->request->params['named']['q'] . '%';
			$this->request->data['ProjectComment']['q'] = $this->request->params['named']['q'];
            $this->pageTitle.= sprintf(__l(' - Search - %s') , $this->request->params['named']['q']);
        }
        if (!empty($this->request->params['named']['project_id'])) {
            $conditions['project_id'] = $this->request->params['named']['project_id'];
        }
        $this->paginate = array(
            'conditions' => $conditions,
            'contain' => array(
                'Project' => array(
                    'ProjectStatus',
                ) ,
                'User',
				'Ip' => array(
                    'City' => array(
                        'fields' => array(
                            'City.name',
                        )
                    ) ,
                    'State' => array(
                        'fields' => array(
                            'State.name',
                        )
                    ) ,
                    'Country' => array(
                        'fields' => array(
                            'Country.name',
                            'Country.iso2',
                        )
                    ) ,
                    'fields' => array(
                        'Ip.ip',
                        'Ip.latitude',
                        'Ip.longitude',
						'Ip.host'
                    )
                ) ,
            ) ,
            'order' => array(
                'ProjectComment.id' => 'desc'
            )
        );
		if (!empty($this->request->data['ProjectComment']['q'])) {
            $this->paginate = array_merge($this->paginate, array(
				'search' => $this->request->data['ProjectComment']['q']
			));
        }
        $moreActions = $this->ProjectComment->moreActions;
        $this->set('suspended', $this->ProjectComment->find('count', array(
            'conditions' => array(
                'ProjectComment.admin_suspend = ' => 1,'ProjectComment.project_id = ' => $this->request->params['named']['project_id']
            )
        )));
        $this->set('system_flagged', $this->ProjectComment->find('count', array(
            'conditions' => array(
                'ProjectComment.is_system_flagged = ' => 1,'ProjectComment.project_id = ' => $this->request->params['named']['project_id']
            )
        )));
        $this->set('total_project_comments', $this->ProjectComment->find('count'));
        $this->set('projectComments', $this->paginate());
        $this->set(compact('moreActions'));
		if(!empty($this->request->params['named']['project_id'])){
		$this->set('project_id',$this->request->params['named']['project_id']);
		}
    }
    public function admin_delete($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if ($this->ProjectComment->delete($id)) {
            $this->Session->setFlash(__l('Project Comment deleted') , 'default', null, 'success');
            $this->redirect(array(
                'action' => 'index'
            ));
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
    }
    public function admin_update()
    {
        if (!empty($this->request->data[$this->modelClass])) {
            $r = $this->request->data[$this->modelClass]['r'];
            $actionid = $this->request->data[$this->modelClass]['more_action_id'];
            unset($this->request->data[$this->modelClass]['r']);
            unset($this->request->data[$this->modelClass]['more_action_id']);
            $selectedIds = array();
            foreach($this->request->data[$this->modelClass] as $primary_key_id => $is_checked) {
                if ($is_checked['id']) {
                    $selectedIds[] = $primary_key_id;
                }
            }
            if ($actionid && !empty($selectedIds)) {
                if ($actionid == ConstMoreAction::Delete) {
                    $this->{$this->modelClass}->deleteAll(array(
                        $this->modelClass . '.id' => $selectedIds
                    ));
                    $this->Session->setFlash(__l('Checked update comments has been deleted') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Suspend) {
                    $this->ProjectComment->updateAll(array(
                        'ProjectComment.admin_suspend' => 1
                    ) , array(
                        'ProjectComment.id' => $selectedIds
                    ));
                    $this->Session->setFlash(__l('Checked project comments has been Suspended') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Unsuspend) {
                    $this->ProjectComment->updateAll(array(
                        'ProjectComment.admin_suspend' => 0
                    ) , array(
                        'ProjectComment.id' => $selectedIds
                    ));
                    $this->Session->setFlash(__l('Checked project comments has been Unsuspended') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Flagged) {
                    $this->ProjectComment->updateAll(array(
                        'ProjectComment.is_system_flagged' => 1
                    ) , array(
                        'ProjectComment.id' => $selectedIds
                    ));
                    $this->Session->setFlash(__l('Checked project comments has been Flagged') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Unflagged) {
                    $this->ProjectComment->updateAll(array(
                        'ProjectComment.is_system_flagged' => 0
                    ) , array(
                        'ProjectComment.id' => $selectedIds
                    ));
                    $this->Session->setFlash(__l('Checked project comments has been Unflagged') , 'default', null, 'success');
                }
            }
        }
        $this->redirect(Router::url('/', true) . $r);
    }
    public function admin_update_stats($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'active')) {
            $this->ProjectComment->updateAll(array(
                'ProjectComment.is_system_flagged' => 1
            ) , array(
                'ProjectComment.id' => $id
            ));
            $this->Session->setFlash(__l('Project comment has been flagged') , 'default', null, 'success');
        } elseif (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'deactivate')) {
            $this->ProjectComment->updateAll(array(
                'ProjectComment.is_system_flagged' => 0
            ) , array(
                'ProjectComment.id' => $id
            ));
            $this->Session->setFlash(__l('Project comment has been Unflagged') , 'default', null, 'success');
        } elseif (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'suspend')) {
            // refund amount
            $this->ProjectComment->updateAll(array(
                'ProjectComment.admin_suspend' => 1
            ) , array(
                'ProjectComment.id' => $id
            ));
            $this->Session->setFlash(__l('Project comment has been suspend') , 'default', null, 'success');
        } elseif (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'unsuspend')) {
            $this->ProjectComment->updateAll(array(
                'ProjectComment.admin_suspend' => 0
            ) , array(
                'ProjectComment.id' => $id
            ));
            $this->Session->setFlash(__l('Project comment has been unsuspend') , 'default', null, 'success');
        }
        $this->redirect(array(
            'action' => 'index',
        ));
    }
}
?>